package com.csis.framework.util.jqgrid;

import com.csis.framework.domain.FormBean;
import com.csis.framework.domain.Page;
import com.csis.framework.util.jqgrid.JqGridResponse.ResponseType;

public class JqGridJSONResponseParser<E, T extends FormBean<E>> extends AbstractFormBeanResponseParser<E, T> {

	@Override
	public JqGridResponse parse(T t) {
		Page page = t.getPage();
		page.prepare();
		StringBuffer buffer = new StringBuffer();
		// --start
		buffer.append("{");
		// total
		buffer.append("\"total\":\"");
		buffer.append(t.getPage().getMaxPage());
		buffer.append("\",");
		// page
		buffer.append("\"page\":\"");
		buffer.append(t.getPage().getCurPage());
		buffer.append("\",");
		// records
		buffer.append("\"records\":\"");
		buffer.append(t.getPage().getCount());
		buffer.append("\",");
		// rows
		buffer.append("\"rows\":");
		buffer.append("[");
		int i = 0;
		for (E e : t.getBeans()) {
			Cell<E> cell = Cell.create(e);
			cell.setSequence((page.getCurPage() - 1) * page.getCount() + (i + 1));
			buffer.append("{\"id\":");
			buffer.append(getFilter().getJqGridCellId(cell));
			buffer.append(",\"cell\":[");
			int j = 0;
			for (Object obj : getFilter().getJqGridCell(cell)) {
				buffer.append("\"");
				buffer.append(obj);
				buffer.append("\"");
				buffer.append(",");
				j++;
			}
			if (j != 0) {
				buffer.delete(buffer.length() - 1, buffer.length());
			}
			buffer.append("]}");
			buffer.append(",");
			i++;
		}
		if (i != 0) {
			buffer.delete(buffer.length() - 1, buffer.length());
		}
		buffer.append("]");
		// --end
		buffer.append("}");

		return JqGridResponse.build(buffer.toString(), ResponseType.JSON);
	}

}
